package com.lucky.common.interceptor;

import com.lucky.common.base.ResultVO;
import com.lucky.common.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.UUID;

@Component
public class TokenInterceptor implements HandlerInterceptor {

	public Logger log = LoggerFactory.getLogger(TokenInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		
		if (handler instanceof HandlerMethod) {

			HandlerMethod handlerMethod = (HandlerMethod) handler;
			Method method = handlerMethod.getMethod();
			Token token = method.getAnnotation(Token.class);
			
			if(token == null) {
				return true;
			}
			
			if(token.value().equals(TokenType.remove) || token.value().equals(TokenType.refresh)) {
				boolean isRepeat = isRepeatSubmit(request);
				if (isRepeat) {
					request.setAttribute("msg", "不可以重复提交");
					handleFalseResponse(response);
					return false;
				}
				request.getSession().removeAttribute("token");
			}
			if(token.value().equals(TokenType.create) || token.value().equals(TokenType.refresh)) {
				request.getSession().setAttribute("token", UUID.randomUUID().toString());
			}
			return true;
		} else {
			return true;
		}
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

	}

	private boolean isRepeatSubmit(HttpServletRequest request) {

		String serverToken = request.getSession().getAttribute("token").toString();
		String clinetToken = request.getParameter("token");
		boolean result = false;
		if (serverToken == null || clinetToken == null || !clinetToken.equals(serverToken)) {
			result = true;
		} 
		return result;
	}

	private void handleFalseResponse(HttpServletResponse response) throws Exception {
		response.setStatus(200);
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");

		response.getWriter().write(JsonUtil.toJson(ResultVO.fail("重复提交！！！")));
		response.getWriter().flush();
	}

}
